#include "png8cropfx.h"
#include "cropctx.h"

namespace png8crop
{
	cropctx::cropctx(imgsource *image)
		:image(image), cropbuf_alloc(NULL)
	{
		this->scale = image->get_size();
	}

	cropctx::~cropctx(void)
	{
		if(cropbuf_alloc != NULL) { delete[] cropbuf_alloc; cropbuf_alloc=NULL; }
	}

	void cropctx::export_crops(const _TCHAR* output_fmt)
	{
		if(this->image == NULL)
		{
			throw ex_internal(_T("Cropping context not atteched to a source before export crops."));
		}

		_TCHAR path_buff[MAX_PATH_EXT];
		FILE* output = NULL;

		for(int i=0; i<this->num_crops; ++i)
		{
			try
			{
				crop thecrop = this->crops[i];

				if(this->scale.w != 0 && this->scale.h != 0)
				{
					float rx, ry;
					size2d imgsize = this->image->get_size();
					rx = (imgsize.w) / (float) (this->scale.w);
					ry = (imgsize.h) / (float) (this->scale.h);

					thecrop.x = (png_uint_32) (thecrop.x * rx);
					thecrop.y = (png_uint_32) (thecrop.y * ry);
					thecrop.w = (png_uint_32) (thecrop.w * rx);
					thecrop.h = (png_uint_32) (thecrop.h * ry);
				}

				if(_stprintf(path_buff, output_fmt, i, thecrop.x, thecrop.y, thecrop.w, thecrop.h) == -1)
				{
					_itot(i, path_buff, 0);
					throw ex_internal(_T("Cannot generate pathname for crop."), path_buff); 
				}

				if ((output = _tfopen(path_buff, _T("wb"))) == NULL)
				{
					throw ex_io(_T("Could not open output file"), path_buff);
				}

				this->image->save(output, &thecrop);

			}
			catch(const ex_generic &ex)
			{
				ex.print_msg();
			}
			
			if(output != NULL)
			{
				fclose(output);
				output = NULL;
			}
		}
	}

	
	void cropctx::load_context(FILE* crpfile)
	{
		if(this->cropbuf_alloc != NULL)
		{
			delete[] this->cropbuf_alloc;
			this->cropbuf_alloc = NULL;
		}

		this->crops = NULL;

		_ftscanf(crpfile, _T("%d,	%d\n"), &this->scale.w, &this->scale.h);

		_ftscanf(crpfile, _T("%d\n"), &this->num_crops);
				
		this->crops = this->cropbuf_alloc = new crop[this->num_crops];
		
		for(int i = 0; i < this->num_crops; ++i)
		{
			_ftscanf(crpfile, _T("%d,	%d,	%d,	%d\n"), &this->crops[i].x, &this->crops[i].y, &this->crops[i].w, &this->crops[i].h);
		}

		return;
	}

	void cropctx::save_context(FILE* crpfile)
	{
		_ftprintf(crpfile, _T("%d,	%d\n"), this->scale.w, this->scale.h);

		_ftprintf(crpfile, _T("%d\n"), this->num_crops);
		
		for(int i = 0; i < this->num_crops; ++i)
		{
			_ftprintf(crpfile, _T("%d,	%d,	%d,	%d\n"), this->crops[i].x, this->crops[i].y, this->crops[i].w, this->crops[i].h);
		}

		return;
	}

}


